﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ElGaleticia.Cipher;
using ElGaleticia.Cipher.Math;
using System.Security.Cryptography;

namespace ElGaleticiaCrypto
{
	public partial class Form1 : Form
	{
		ElGamal.EG_Secret_Key secretKey;
		BigInteger biData;
		ElGamal elga;

		public Form1()
		{
			InitializeComponent();
			elga = new ElGamal();
			button2.Enabled = false;
		}

		private void textBox1_TextChanged(object sender, EventArgs e)
		{
			biData = new BigInteger(System.Text.Encoding.UTF8.GetBytes(textBox1.Text));
		}

		private void button1_Click(object sender, EventArgs e)
		{
			//gera uma chave privada de tamanho 256bit = 32bytes
			secretKey = ElGamal.GenerateKey(256);

			//gera a chave publica de uma dada chave privada
			ElGamal.EG_Public_Key publicKey = ElGamal.secKey2Pub(secretKey);

			textBox3.Text = Convert.ToBase64String(ElGamal.formatEGPubKey(0, publicKey));

			button2.Enabled = true;
		}

		private void button3_Click(object sender, EventArgs e)
		{
			try
			{
				ElGamal.EG_Public_Key publicKey = ElGamal.parseEGPubKey(Convert.FromBase64String(textBox3.Text));
				BigInteger[] biEnc = elga.Encrypt(biData, publicKey);
				textBox4.Text = Convert.ToBase64String(biEnc[0].getBytes());
				textBox2.Text = Convert.ToBase64String(biEnc[1].getBytes());
			}
			catch (FormatException)
			{
				DialogResult dialog = MessageBox.Show("A chave pública está com defeito!");
			}
		}

		private void button2_Click(object sender, EventArgs e)
		{
			try
			{
				BigInteger[] biEnc = new BigInteger[2];
				biEnc[0] = new BigInteger(Convert.FromBase64String(textBox4.Text));
				biEnc[1] = new BigInteger(Convert.FromBase64String(textBox2.Text));
				ElGamal.EG_Public_Key publicKey = ElGamal.parseEGPubKey(Convert.FromBase64String(textBox3.Text));
				BigInteger biDec = elga.Decrypt(biEnc, secretKey);
				textBox1.Text = System.Text.Encoding.UTF8.GetString(biDec.getBytes());
			}
			catch (FormatException)
			{
				DialogResult dialog = MessageBox.Show("A chave pública está com defeito!");
			}
		}
	}
}
